﻿<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="true" EnableSessionState="True" CodeBehind="Orders.aspx.cs" Inherits="famails.BackEnd.Customer.Orders" MasterPageFile="~/Master.Master" %>


<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <style>
        #dropDownButtonContentdropDownButton div {
            margin-top: 2px !important;
        }
    </style>
    <div style="width: 100%; padding: 10px;">

        <div class="col-md-12 col-xs-12 col-sm-12 col-lg-12" style="border: 1px solid #333; margin-bottom: 10px; padding: 0px;">
            <div class="col-md-12 col-xs-12 col-sm-12 col-lg-12" style="padding: 10px 20px; background: #000; color: #fff; font-size: 18px; font-weight: bold; position: relative;">
                Thêm đơn hàng
            </div>
            <div class="col-md-12 col-xs-12 col-sm-12 col-lg-12" style="height: auto; padding: 10px;">
                <asp:HiddenField ID="hdfCustomerId" runat="server" />
                <asp:HiddenField ID="hdfOrderID" runat="server" />
                <asp:Panel Visible="false" ID="pnError" runat="server">
                    <div class="error-box round">
                        <asp:Label ID="lblError" runat="server" Text=""></asp:Label>
                    </div>
                </asp:Panel>
                <asp:Panel Visible="false" ID="pnSuccess" runat="server">
                    <div class="confirmation-box round">
                        <asp:Label ID="lblSuccess" runat="server" Text=""></asp:Label>
                    </div>
                </asp:Panel>
            </div>

            <div class="col-md-6 col-xs-12 col-sm-6 col-lg-6" style="height: auto; padding: 10px;">
                <fieldset>
                    <label for="simple-input" style="font-weight: bolder; text-transform: none">
                        Mã đơn hàng</label>
                    <asp:TextBox ID="txtOrderCode" CssClass="form-control" Style="border: 1px solid #333; border-radius: 0px;" runat="server"></asp:TextBox>
                    <em style="color: #333;">Mã đơn hàng</em>
                </fieldset>
            </div>
            <div class="col-md-6 col-xs-12 col-sm-6 col-lg-6" style="height: auto; padding: 10px;">
                <fieldset>
                    <label for="simple-input" style="font-weight: bolder; text-transform: none">
                        Mã giao hàng</label>
                    <asp:TextBox ID="txtDeliveryCode" CssClass="form-control" Style="border: 1px solid #333; border-radius: 0px;" runat="server"></asp:TextBox>
                    <em style="color: #333;">Mã giao hàng</em>
                </fieldset>

            </div>
            <div class="col-md-3 col-xs-12 col-sm-3 col-lg-3" style="height: auto; padding: 10px;">
                <fieldset>
                    <label for="simple-input" style="font-weight: bolder; text-transform: none">
                        Tiền cọc</label>
                    <div id="txtDeposit" style="border: 1px solid #333; height: 32px !important; border-radius: 0px;" class="form-control"></div>

                </fieldset>
            </div>
            <div class="col-md-3 col-xs-12 col-sm-3 col-lg-3" style="height: auto; padding: 10px;">
                <fieldset>
                    <label for="simple-input" style="font-weight: bolder; text-transform: none">
                        Phương thức thanh toán</label>
                    <asp:DropDownList ID="ddlPayment" runat="server" CssClass="form-control" Style="-webkit-appearance: none; border: 1px solid #333; border-radius: 0px;">
                        <asp:ListItem Value="Tiền mặt">Tiền mặt</asp:ListItem>
                        <asp:ListItem Value="Chuyển khoản">Chuyển khoản</asp:ListItem>
                        <asp:ListItem Value="Khác">Khác</asp:ListItem>
                    </asp:DropDownList>
                </fieldset>
            </div>
            <div class="col-md-3 col-xs-12 col-sm-3 col-lg-3" style="height: auto; padding: 10px;">
                <fieldset>
                    <label for="simple-input" style="font-weight: bolder; text-transform: none">
                        Phương thức giao hàng</label>
                    <asp:DropDownList ID="ddlDelivery" runat="server" CssClass="form-control" Style="-webkit-appearance: none; border: 1px solid #333; border-radius: 0px;">
                        <asp:ListItem Value="Giao hàng tận nơi">Giao hàng tận nơi</asp:ListItem>
                        <asp:ListItem Value="Qua đường bưu điện">Qua đường bưu điện</asp:ListItem>
                        <asp:ListItem Value="Khác">Khác</asp:ListItem>
                    </asp:DropDownList>
                </fieldset>
            </div>
            <div class="col-md-3 col-xs-12 col-sm-3 col-lg-3" style="height: auto; padding: 10px;">
                <fieldset>
                    <label for="simple-input" style="font-weight: bolder; text-transform: none">
                        Phí giao hàng</label>
                    <div id="txtDeliveryFee" style="border: 1px solid #333; height: 32px !important; border-radius: 0px;" class="form-control"></div>
                </fieldset>
            </div>
            <div class="col-md-3 col-xs-12 col-sm-6 col-lg-3" style="height: auto; padding: 10px;">
                <fieldset>
                    <label for="simple-input" style="font-weight: bolder; text-transform: none">
                        Trạng thái</label>
                    <asp:DropDownList ID="ddlStatus" runat="server" CssClass="form-control" Style="-webkit-appearance: none; border: 1px solid #333; border-radius: 0px;">
                        <asp:ListItem Value="Đã giao hàng">Đã giao hàng</asp:ListItem>
                        <asp:ListItem Value="Chưa giao hàng">Chưa giao hàng</asp:ListItem>
                    </asp:DropDownList>
                </fieldset>
            </div>
            <div class="col-md-3 col-xs-12 col-sm-6 col-lg-3 pull-right" style="height: auto; padding: 10px;">
                <fieldset>
                    <label for="simple-input" style="font-weight: bolder; text-transform: none">
                        Đối tượng giao hàng</label>
                    <div class="col-md-12" style="padding: 6px;">
                        <input id="rdReciever" type="radio" style="margin-right: 10px;" name="ojb_send" onclick="giao(this.value);" value="0" checked="checked" /><label for="rdReciever" style="margin-right: 10px;">Khách hàng</label>
                        <input id="rdReciever_other" type="radio" style="margin-right: 10px;" name="ojb_send" onclick="giao(this.value);" value="1" /><label for="rdReciever_other" style="margin-right: 10px;">Khác</label>

                    </div>
                    <%--<asp:TextBox ID="address_giao" TextMode="multiline" Rows="3" CssClass="form-control" Style="visibility:hidden;border: 1px solid #333; border-radius: 0px;" runat="server"></asp:TextBox>--%>
                </fieldset>
            </div>
            <div class="col-md-6 col-xs-12 col-sm-6 col-lg-6" style="height: auto; padding: 10px;">
                <fieldset>
                    <label for="simple-input" style="font-weight: bolder; text-transform: none">
                        Khách hàng</label>
                    <div id='jqxWidget' class="form-control" style="border: 1px solid #333; border-radius: 0px; height: 20px !important;">
                    </div>

                </fieldset>
            </div>
            <div class="col-md-2 col-xs-12 col-sm-3 col-lg-2" style="height: auto; padding: 0px;">
                <div class="col-md-12 col-xs-12 col-sm-12 col-lg-12" style="height: auto; padding: 10px;">
                    <fieldset>
                        <label for="simple-input" style="font-weight: bolder; text-transform: none">
                            Ngày mua hàng</label>
                        <div id="txtOrderDate"></div>
                    </fieldset>
                </div>
                <div class="col-md-12 col-xs-12 col-sm-12 col-lg-12" style="height: auto; padding: 10px;">
                    <fieldset>
                        <label for="simple-input" style="font-weight: bolder; text-transform: none">
                            Ngày giao hàng</label>
                        <div style="margin-bottom: 10px;" id="txtDeliveryDate"></div>
                    </fieldset>
                </div>
            </div>
            <div class="col-md-2 col-xs-12 col-sm-3 col-lg-2" style="height: auto; padding: 0px;">
                <div class="col-md-12 col-xs-12 col-sm-12 col-lg-12" style="height: auto; padding: 10px;">
                    <fieldset>
                        <label for="simple-input" style="font-weight: bolder; text-transform: none">
                            Người nhận hàng</label>
                        <input type="text" class="form-control" disabled="disabled" style="border: 1px solid #333; border-radius: 0px;" id="txt_name_other"></input>
                    </fieldset>
                </div>
                <div class="col-md-12 col-xs-12 col-sm-12 col-lg-12" style="height: auto; padding: 10px;">
                    <fieldset>
                        <label for="simple-input" style="font-weight: bolder; text-transform: none">
                            Số điện thoại</label>
                        <input type="text" class="form-control" disabled="disabled" style="border: 1px solid #333; border-radius: 0px;" id="txt_phone_other"></input>
                    </fieldset>
                </div>
            </div>
            <div class="col-md-4 col-xs-12 col-sm-6 col-lg-4" style="height: auto; padding: 10px;">
                <fieldset>
                    <label for="simple-input" style="font-weight: bolder; text-transform: none">
                        Địa chỉ người nhận</label>
                    <asp:TextBox ID="txt_address_other" disabled="disabled" TextMode="multiline" Rows="5" CssClass="form-control" Style="border: 1px solid #333; border-radius: 0px;" runat="server"></asp:TextBox>

                </fieldset>
            </div>
            <div class="col-md-4 col-xs-12 col-sm-6 col-lg-4 pull-right" style="height: auto; padding: 10px;">
                <fieldset>
                    <label for="simple-input" style="font-weight: bolder; text-transform: none">
                        Ghi chú</label>
                    <asp:TextBox ID="txtNote" TextMode="multiline" Rows="5" CssClass="form-control" Style="border: 1px solid #333; border-radius: 0px;" runat="server"></asp:TextBox>

                </fieldset>
            </div>
            <div class="col-md-12 col-lg-12 col-sm-12 col-xs-12" style="padding: 10px">
                <div class="col-lg-2 col-md-3 col-sm-4 col-xs-12" style="padding: 0px 5px;">
                    Nhóm sản phẩm
                        <div id="dropDownButton" class="form-control" style="background: #fff; color: #333; border: 1px solid #333; border-radius: 0px; height: 32px;">
                            <div id="jqxTree">
                            </div>
                        </div>
                </div>
                <input type="hidden" name="groupid" id="groupid" value="-1" />

                <div class="col-lg-2 col-md-3 col-sm-4 col-xs-12" style="padding-left: 5px;">
                    Mã sản phẩm:<div id="ccbProduct" class="form-control" style="height: 20px !important; padding: 4px; border: 1px solid #333; border-radius: 0px;"></div>
                </div>
                <div class="col-lg-3 col-md-2 col-sm-4 col-xs-12" style="padding: 0px 5px">
                    Tên sản phẩm:
                    <div>
                        <input type="text" style="border: 1px solid #333; border-radius: 0px;" class="form-control" id="txtProductName" />
                    </div>
                </div>
                <div class="col-lg-1  col-md-1 col-sm-2 col-xs-12" style="padding: 0px 5px;">
                    SL:<div id="txtQty" style="width: 100% !important; border: 1px solid #333; height: 32px !important; border-radius: 0px;" class="form-control"></div>
                </div>
                <div class="col-lg-1 col-md-1 col-sm-4 col-xs-12" style="padding: 0px 5px 0px 5px;">
                    VAT:                            
                   <div id="txtVAT" style="border: 1px solid #333; border-radius: 0px;"></div>
                </div>
                <div class="col-lg-2 col-md-2 col-sm-3 col-xs-12 " style="padding: 0px 5px;">
                    Giá:<div id="txtPrice" style="border: 1px solid #333; height: 32px !important; border-radius: 0px;" class="form-control"></div>
                </div>
                <div class="col-lg-1 col-md-2 col-sm-3 col-xs-12 pull-right" style="padding: 0px; padding-top: 20px;">
                    <div id="btnAddProduct" class="btn pull-right" style="padding: 6px 16px; border: 1px solid #333; border-radius: 0px; background: #333; color: #fff;">
                        <span style="margin-right: 10px;" class="fa fa-plus"></span>Thêm 
                    </div>
                </div>
            </div>
            <div class="col-md-12 col-xs-12 col-sm-12 col-lg-12" style="height: auto; padding: 10px 10px 10px 10px; border-bottom: 1px solid #333; border-top: 1px solid #333;">
                <div class="col-lg-3 col-md-3 col-sm-12 col-xs-12" style="padding: 0px;">

                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style="height: auto; padding: 10px 0px;">
                        <fieldset>
                            <label for="simple-input" style="font-weight: bolder; text-transform: none">Mã giảm giá</label>
                            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style="height: auto; padding: 0px;">
                                <div class="col-lg-6 col-md-6 col-sm-7 col-xs-7" style="padding: 0px;">
                                    <input id="txtDiscountCode" class="form-control" type="text" style="border: 1px solid #333; border-radius: 0px;" />
                                </div>
                                <div class="col-lg-6 col-md-6 col-sm-5 col-xs-5" style="padding: 0px;">
                                    <div class="btn pull-left" id="btnCheckDiscountCode" style="margin-left: 10px; padding: 6px 14px; border: 1px solid #333; border-radius: 0px; background: #333; color: #fff;">
                                        <span style="margin-right: 10px;" class="fa fa-search"></span>Kiểm tra
                                    </div>
                                </div>
                            </div>
                        </fieldset>
                    </div>
                </div>
                <div class="col-lg-3 col-md-3 col-sm-12 col-xs-12" style="padding: 0px 10px;">
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style="height: auto; padding: 10px 0px;">
                        <label for="simple-input" style="font-weight: bolder; text-transform: none">Giảm giá</label>
                        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style="height: auto; padding: 0px;">
                            <input id="txtDiscountValue" readonly="readonly" class="form-control" type="text" style="border: 1px solid #333; border-radius: 0px;" />
                        </div>
                    </div>
                </div>
                <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12" style="padding: 0px;">
                    <div class="col-md-4 col-xs-12 col-sm-4 col-lg-4" style="height: auto; padding: 10px 10px;">
                        <fieldset>
                            <label for="simple-input" style="font-weight: bolder; text-transform: none">
                                Giá trước thuế</label>
                            <div id="txtAmount" style="border: 1px solid #333; height: 32px !important; border-radius: 0px;" class="form-control"></div>
                        </fieldset>
                    </div>
                    <div class="col-md-4 col-xs-12 col-sm-4 col-lg-4" style="height: auto; padding: 10px 10px;">
                        <fieldset>
                            <label for="simple-input" style="font-weight: bolder; text-transform: none">
                                Thuế VAT</label>
                            <div id="txtVATAmount" style="border: 1px solid #333; height: 32px !important; border-radius: 0px;" class="form-control"></div>
                        </fieldset>
                    </div>
                    <div class="col-md-4 col-xs-12 col-sm-4 col-lg-4" style="height: auto; padding: 10px 10px;">
                        <fieldset>
                            <label for="simple-input" style="font-weight: bolder; text-transform: none">
                                Tổng giá trị</label>
                            <div id="txtTotalAmount" style="border: 1px solid #333; height: 32px !important; border-radius: 0px;" class="form-control"></div>
                        </fieldset>
                    </div>
                    <%--<div class="col-md-2 col-xs-12 col-sm-2 col-lg-2" style="height: auto; padding: 10px;">
                        <fieldset>
                            <asp:TextBox ID="txtdiscount" CssClass="form-control" style="border:1px solid #333;border-radius:0px;" 
                        runat="server"></asp:TextBox><span style="position:absolute;right:20px;top:47%;">%</span>
                        </fieldset>
                    </div>--%>
                </div>
            </div>
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" id="jqxgrid"></div>
            <input type="hidden" name="productid" id="productid" value="0" />

            <div class="col-md-12 col-xs-12 col-sm-12 col-lg-12" style="height: auto; padding: 5px;">
                <div id="btnReset" class="btn pull-right" style="margin-right: 10px; padding: 7px 14px; border: 1px solid #333; border-radius: 0px; background: #333; color: #fff;">
                    <span style="margin-right: 10px;" class="fa fa-refresh"></span>Nhập lại
                </div>
                <div id="btnSave" class="btn  pull-right" style="margin-right: 10px; padding: 7px 14px; border: 1px solid #333; border-radius: 0px; background: #333; color: #fff;">
                    <span style="margin-right: 10px;" class="fa fa-save"></span>Lưu
                </div>
            </div>
            <div>
                <asp:HiddenField runat="server" ID="order" />
                <asp:HiddenField runat="server" ID="delivery" />
            </div>
        </div>
        <style>
            #dropdownlistArrowjqxWidget {
                background: none;
            }

            #dropdownlistWrapperjqxWidget {
                margin-top: -2px;
            }

            #jqx-icon-arrow-down {
                background: #000;
                color: #f00;
            }

            #dropdownlistContentjqxWidget {
                border: 0px;
            }

            #dropdownlistContentccbProduct {
                border: 0px;
            }

            #dropdownlistArrowccbProduct {
                background: none;
            }

            .jqx-input-content {
                width: 100% !important;
            }
        </style>
    </div>
    <input type="hidden" id="minVal" />
    <input type="hidden" id="discounttype" />
    <input type="hidden" id="DiscountAmount" />
    <script type="text/javascript">

        jQuery(function ($) {
            loadCustomer();

            function getQueryStrings() {
                var assoc = {};
                var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
                var queryString = location.search.substring(1);
                var keyValues = queryString.split('&');

                for (var i in keyValues) {
                    var key = keyValues[i].split('=');
                    if (key.length > 1) {
                        assoc[decode(key[0])] = decode(key[1]);
                    }
                }

                return assoc;
            }
            var qs = getQueryStrings();
            var orderID = qs["Id"];
            var discounttype = 0; var minVal = 0;
            $("#btnCheckDiscountCode").click(function () {
                if (orderID == undefined)
                    orderID = 0;
                var orderdate = $("#txtOrderDate").jqxDateTimeInput("getText") + "";
                if (orderdate == "") { alert('Vui lòng nhập ngày đặt hàng!'); return; }
                var code = $("#txtDiscountCode").val() + "";
                if (code == "") { alert('Vui lòng nhập mã khuyến mãi!'); return; }
                //alert(orderdate); alert(code);
                var url = "Orders.aspx/CheckDiscountCode";
                var data = "{id:" + orderID + ", code:'" + code + "', orderDate: '" + orderdate + "'}";
                //alert(data);
                $.ajax({
                    type: "POST",
                    url: url,
                    data: data,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        discounttype = data.d.Fix0_Per1;
                        minVal = data.d.MinAmount;
                        $("#minVal").val(minVal);
                        $("#discounttype").val(discounttype);
                        $("#txtDiscountValue").val(data.d.DiscountValue);
                        sumTotalAmount();
                    },
                    error: function (error) {
                        alert('Mã khuyến mãi không hợp lệ!'); $("#txtDiscountValue").val(0); $("#txtDiscountCode").val('');
                    }
                });
            });
            function load4Edit() {
                if (orderID > 0) {
                    var url = "Orders.aspx/Load4Edit";
                    $.ajax({
                        type: "POST",
                        url: url,
                        data: "{id:" + orderID + "}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            $("#ContentPlaceHolder1_txtOrderCode").val(data.d.OrderCode);
                            $("#jqxWidget").val(data.d.CustomerID);
                            //alert($("#jqxWidget").val());
                            //alert(data.d.CustomerID);
                            $("#txtTotalAmount").val(data.d.Amount);
                            $("#txtDeposit").val(data.d.Deposit);
                            $("#txtDeliveryFee").val(data.d.DeliveryFee);
                            var myDate = new Date(data.d.DeliveryDate.match(/\d+/)[0] * 1);
                            $("#txtDeliveryDate").jqxDateTimeInput('val', myDate);
                            myDate = new Date(data.d.OrderDate.match(/\d+/)[0] * 1);
                            $("#txtOrderDate").jqxDateTimeInput('val', myDate);
                            $("#ContentPlaceHolder1_ddlDelivery").val(data.d.Delivery);
                            $("#ContentPlaceHolder1_ddlPayment").val(data.d.Payment);
                            $("#ContentPlaceHolder1_ddlStatus").val(data.d.Status);
                            $("#ContentPlaceHolder1_txtDeliveryCode").val(data.d.DeliveryCode);
                            $("#ContentPlaceHolder1_txtNote").val(data.d.Note);

                            if (data.d.Reciever)
                                $("#rdReciever").prop('checked', true);
                            else { $("#rdReciever_other").prop('checked', true); giao(1); }
                            $("#txt_name_other").val(data.d.RecieverName);
                            $("#txt_phone_other").val(data.d.RecieverPhone);
                            $("#ContentPlaceHolder1_txt_address_other").val(data.d.RecieverAddress);
                            $("#txtDiscountCode").val(data.d.DiscountCode);
                            $("#txtDiscountValue").val(data.d.DiscountValue);

                            $("#minVal").val(data.d.MinAmount);
                            $("#discounttype").val(data.d.Fix0_Per1);

                            datasource = data.d.Items;
                            sumTotalAmount();
                            loadGrid();
                        },
                        error: function (error) {
                            alert(error.d);
                        }
                    });
                }
            }
            function reset() {
                //$("#ContentPlaceHolder1_txtOrderCode").val("");
                //$("#jqxWidget").jqxComboBox({ selectedIndex: -1 });
                $("#txtAmount").val(0);
                $("#txtDeposit").val(0),
                $("#txtDeliveryFee").val(0),
                //$("#txtDeliveryDate").val(Date.now),
                // $("#txtOrderDate").val(Date.now),
                //$("#ContentPlaceHolder1_ddlDelivery").selectedIndex = 0;
                //$("#ContentPlaceHolder1_ddlPayment").selectedIndex = 0;
                //$("#ContentPlaceHolder1_ddlStatus").selectedIndex = 0;
                //$("#ContentPlaceHolder1_txtDeliveryCode").val("");
                $("#ContentPlaceHolder1_txtNote").val("");
                datasource = []; $("#jqxgrid").jqxGrid("clear");
                $("#ContentPlaceHolder1_txtOrderCode").focus();
            }
            $("#btnReset").click(function () {
                if (orderID > 0)
                    load4Edit();
                else reset();
            });

            function checkBeforSave(postData) {
                var errorMessage = "";
                if (postData.OrderCode == "")
                    errorMessage = "Chưa nhập mã đơn hàng";
                else {
                    var post = "{code:'" + postData.OrderCode + "', orderid:" + postData.OrderID + "}";
                    var exist = function () {
                        var count = 0;
                        var url = "Orders.aspx/CheckExistsOrderCode";
                        //alert(post);
                        $.ajax({
                            async: false,
                            type: "POST",
                            global: false,
                            url: url,
                            data: post,
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (data) {
                                count = parseInt(data.d);
                            }
                        });
                        //alert(count);
                        return count > 0;
                    }();
                    if (exist)
                        errorMessage = "Trùng mã đơn hàng";
                    else if (parseInt(postData.Amount) < 0)
                        errorMessage = "Giá trị đơn hàng không hợp lệ";
                    else if (parseInt(postData.Amount) - parseInt(postData.Deposit) < 0)
                        errorMessage = "Tiền cọc không được lớn hơn giá trị đơn hàng";
                    else if (postData.DeliveryDate == "")
                        errorMessage = "Ngày giao hàng không hợp lệ";
                    else if (postData.OrderDate == "")
                        errorMessage = "Ngày đặt hàng không hợp lệ";
                    else if (postData.CustomerID + "" == "")
                        errorMessage = "Chưa nhập khách hàng";
                    else if (postData.Items.length == 0)
                        errorMessage = "Chưa nhập sản phẩm";
                    else if (!postData.Reciever) {
                        if (postData.RecieverName == undefined)
                            errorMessage = "Chưa nhập tên người nhận";
                        else if (postData.RecieverPhone == undefined)
                            errorMessage = "Chưa nhập số điện thoại người nhận";
                        else if (postData.RecieverAddress == undefined)
                            errorMessage = "Chưa nhập địa chỉ người nhận";
                    }
                    if (errorMessage.length == 0)
                        if (parseInt(postData.DiscountAmount) == 0) {
                            if (postData.DiscountCode != "" && parseInt(postData.MinAmount) > 0) alert("Giá trị đơn hàng tối thiểu cho chương trình khuyến mãi này là :" + postData.MinAmount + ". Đơn hàng này sẽ không được áp dụng khuyến mãi!");
                            postData.DiscountCode = "";
                            postData.MinAmount = 0;
                            postData.Fix0_Per1 = 0;
                            postData.DiscountValue = 0;
                        }
                }
                if (errorMessage.length > 0) {
                    alert(errorMessage);
                }
                return errorMessage.length == 0;
            }
            $("#btnSave").click(function () {

                //var vat = $("#txtVAT").val();
                //var qty = $("#txtQty").val();
                //var price = $("#txtPrice").val();
                //var total = (price * qty) + (price * qty * vat / 100);
                var postData = {
                    OrderCode: $("#ContentPlaceHolder1_txtOrderCode").val(),
                    OrderID: orderID == undefined ? 0 : orderID,
                    CustomerID: $("#jqxWidget").val(),
                    Amount: $("#txtTotalAmount").val(),
                    Deposit: $("#txtDeposit").val(),
                    DeliveryFee: $("#txtDeliveryFee").val(),
                    DeliveryDate: $("#txtDeliveryDate").val(),
                    OrderDate: $("#txtOrderDate").val(),
                    Delivery: $("#ContentPlaceHolder1_ddlDelivery").val(),
                    Payment: $("#ContentPlaceHolder1_ddlPayment").val(),
                    Status: $("#ContentPlaceHolder1_ddlStatus").val(),
                    DeliveryCode: $("#ContentPlaceHolder1_txtDeliveryCode").val(),
                    Note: $("#ContentPlaceHolder1_txtNote").val(),
                    DiscountValue: $("#txtDiscountValue").val(),
                    DiscountCode: $("#txtDiscountCode").val(),
                    DiscountAmount: $("#DiscountAmount").val(),
                    MinAmount: minVal,
                    Fix0_Per1: discounttype,
                    RecieverName: $("#txt_name_other").val(),
                    RecieverPhone: $("#txt_phone_other").val(),
                    RecieverAddress: $("#ContentPlaceHolder1_txt_address_other").val(),
                    Reciever: $('#rdReciever').is(':checked') ? true : false,
                    Items: datasource
                };
                if (checkBeforSave(postData)) {
                    var url = "Orders.aspx/SaveOrder";
                    $.ajax({
                        type: "POST",
                        url: url,
                        data: "{json:'" + JSON.stringify(postData) + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            alert(data.d);
                            if (orderID == undefined)
                                reset();

                        }, error: function (xhr, errorType, exception) { //Triggered if an error communicating with server  
                            var errorMessage = exception || xhr.statusText; //If exception null, then default to xhr.statusText  

                            alert("Có lỗi trong quá trình tạo đơn hàng: " + errorMessage);
                        }
                    });
                }
            });
            var datasource = [];
            function removeProduct(code) {
                var newsource = [];
                for (var i = 0; i < datasource.length; i++) {
                    //alert(datasource[i].ProductCode);
                    //alert(code);
                    if (datasource[i].ProductCode != code) {
                        if (newsource.length == 0)
                            newsource[0] = datasource[i];
                        else newsource[newsource.length] = datasource[i];
                    }
                }
                //alert(newsource.length);
                datasource = newsource;
                sumTotalAmount();
            }
            function sumTotalAmount() {
                minVal = parseInt($("#minVal").val());
                discounttype = parseInt($("#discounttype").val());
                var vat = parseInt($("#txtVAT").val());
                var qty = parseInt($("#txtQty").val());
                var price = parseInt($("#txtPrice").val());

                var amount = qty * price;
                var vatAmount = amount * vat / 100;
                var totalAmount = amount + vatAmount;
                for (var i = 0; i < datasource.length; i++) {
                    amount += parseInt(datasource[i].Qty) * parseInt(datasource[i].Price);
                    vatAmount += parseInt(datasource[i].VATAmount);
                    totalAmount = amount + vatAmount;
                }
                var discountvalue = parseInt($("#txtDiscountValue").val());
                if (discountvalue + '' == '') discountvalue = 0;
                if (minVal == undefined) minVal = 0;
                if (discounttype == 0)
                    if (amount > minVal)
                        discountvalue = discountvalue;
                    else discountvalue = 0;
                else
                    if (amount > minVal)
                        discountvalue = (amount * discountvalue / 100);
                    else discountvalue = 0;
                totalAmount = totalAmount - discountvalue;

                $("#txtAmount").val(amount);
                $("#txtVATAmount").val(vatAmount);
                $("#txtTotalAmount").val(totalAmount);
                $("#DiscountAmount").val(discountvalue);
            }
            function sumAmount() {
                var vat = $("#txtVAT").val();
                var qty = $("#txtQty").val();
                var price = $("#txtPrice").val();

                var amount = parseInt($("#txtAmount").val());
                var vatAmount = parseInt($("#txtVATAmount").val());
                vatAmount += parseInt(qty) * parseInt(price) * parseInt(vat) / 100;
                amount += parseInt(qty) * parseInt(price);

                var totalAmount = amount + vatAmount;
                var discountvalue = parseInt($("#txtDiscountValue").val());
                if (discounttype == 0)
                    if (totalAmount > minVal)
                        discountvalue = totalAmount - discountvalue;
                    else discountvalue = totalAmount;
                else
                    if (totalAmount > minVal)
                        discountvalue = totalAmount - (totalAmount * discountvalue / 100);
                    else discountvalue = totalAmount;
                totalAmount = discountvalue;

                $("#txtAmount").val(amount);
                $("#txtVATAmount").val(vatAmount);
                $("#txtTotalAmount").val(totalAmount);
            }
            $('#txtPrice').on('change', function (event) {
                sumTotalAmount();
            });
            $('#txtQty').on('change', function (event) {
                var value = event.args.value;
                sumTotalAmount();
            });
            $('#txtVAT').on('change', function (event) {
                var value = event.args.value;
                sumTotalAmount();
            });
            $("#btnAddProduct").click(function () {


                var vat = parseInt($("#txtVAT").val());
                var qty = parseInt($("#txtQty").val());
                var price = parseInt($("#txtPrice").val());

                var object = {
                    ProductID: $("#productid").val(),
                    ProductCode: $("#ccbProduct").val(),
                    GroupID: $("#groupid").val(),
                    ProductName: $("#txtProductName").val(),
                    Price: $("#txtPrice").val(),
                    Qty: $("#txtQty").val(),
                    VAT: $("#txtVAT").val(),
                    VATAmount: qty * price * vat / 100,
                    Amount: qty * price + (qty * price * vat / 100)
                };
                //check data
                if (object.ProductCode == "") { alert('Chưa nhập mã sản phẩm'); return; }
                if (object.ProductName == "") { alert('Chưa nhập sản phẩm'); return; }
                if (parseInt(object.Price) <= 0) { alert('Chưa nhập giá'); return; }
                if (parseInt(object.Qty) <= 0) { alert('Chưa nhập số lượng'); return; }
                var add = false;
                for (var i = 0; i < datasource.length; i++) {
                    if (datasource[i].ProductCode == object.ProductCode) {
                        datasource[i].Qty += object.Qty;
                        add = true;
                    }
                }
                if (!add)
                    if (datasource.length == 0)
                        datasource[0] = object;
                    else datasource[datasource.length] = object;
                sumTotalAmount();
                loadGrid();

                $('#txtProductName').prop('readonly', false);
                $('#txtPrice').jqxNumberInput({ readOnly: false });
                $("#ccbProduct").jqxComboBox({ selectedIndex: -1 });
                $('#txtProductName').val("");
                $('#txtPrice').val(0); $('#txtQty').val(0);

            });
            function loadGrid() {
                var source =
                {
                    datatype: "json",
                    ID: "ProductCode",
                    localdata: datasource
                };
                var dataAdapter = new $.jqx.dataAdapter(source);

                //source.add(object);
                $("#jqxgrid").jqxGrid(
                    {
                        width: '100%',
                        source: dataAdapter,
                        selectionmode: 'multiplerowsextended',
                        sortable: true,
                        pageable: true,
                        autoheight: true,
                        columnsresize: true,
                        columns: [
                          { text: 'Mã sản phẩm', datafield: 'ProductCode' },
                          { text: 'Tên sản phẩm', datafield: 'ProductName' },
                          { text: 'Số lượng', datafield: 'Qty', cellsformat: 'number', cellsalign: 'right', width: 120 },
                          { text: 'Đơn giá', datafield: 'Price', cellsformat: 'number', cellsalign: 'right', width: 120 },
                          { text: 'Thuế', datafield: 'VATAmount', width: 120, cellsformat: 'number', cellsalign: 'right' },
                          { text: 'Tổng giá trị', width: 120, datafield: 'Amount', cellsformat: 'number', cellsalign: 'right' },
                          {
                              text: 'Xóa', datafield: 'Delete', columntype: 'button', width: 50, cellsrenderer: function () {
                                  return "Xóa";
                              }, buttonclick: function (row) {
                                  // open the popup window when the user clicks a button.
                                  id = $("#jqxgrid").jqxGrid('getrowid', row);
                                  code = $("#jqxgrid").jqxGrid('getcellvalue', row, "ProductCode");
                                  removeProduct(code);
                                  $('#jqxgrid').jqxGrid('deleterow', id);
                              }
                          }]
                    });
            }
            function loadCustomer() {
                var url = "Orders.aspx/LoadCustomer";
                $.ajax({
                    type: "POST",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        var source =
                        {
                            datatype: "json",
                            datafields: [
                                { name: 'CustomerID', type: 'decimal' },
                                { name: 'CustomerName', type: 'string' },
                                { name: 'Email', type: 'string' }
                            ],
                            id: 'CustomerID',
                            localdata: data
                        };
                        var dataAdapter = new $.jqx.dataAdapter(source);
                        // Create a jqxComboBox
                        $("#jqxWidget").jqxComboBox({ height: '20', selectedIndex: -1, source: dataAdapter, placeHolder: "Tên khách hàng", displayMember: "Email", valueMember: "CustomerID", width: '90%' });
                        $("#jqxWidget").jqxComboBox({ searchMode: "containsignorecase" });
                        //$("#jqxWidget").jqxComboBox('focus');
                    }
                });
            }
            load4Edit();
            function loadProduct() {
                var post = "{groupid:" + ($("#groupid").val() == "" ? -1 : $("#groupid").val()) + "}";
                //alert(post);
                $.ajax({
                    type: "POST",
                    url: 'orders.aspx/LoadProduct',
                    data: post,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        var source =
                        {
                            localdata: data
                        };
                        var dataAdapter = new $.jqx.dataAdapter(source);

                        // Create a jqxComboBox
                        $("#ccbProduct").jqxComboBox({ selectedIndex: -1, source: data.d, height: 25, width: 150, dropDownWidth: 250 });
                        $("#ccbProduct").jqxComboBox({ searchMode: "equals" });
                    }
                });
            }
            $("#txtOrderDate").jqxDateTimeInput({ width: '120px', height: '34px' });
            $("#txtDeliveryDate").jqxDateTimeInput({ width: '120px', height: '34px' });
            $("#txtQty").jqxNumberInput({
                height: '32px', value: 0,
                decimalDigits: 0, min: 0, digits: 3
            });
            $("#txtPrice").jqxNumberInput({ height: '34px', value: 0, max: 100000000000, digits: 11, min: 0 });
            $("#txtAmount").jqxNumberInput({ height: '34px', value: 0, readOnly: true, max: 1000000000000, digits: 12, min: 0 });
            $("#txtVATAmount").jqxNumberInput({ height: '34px', value: 0, readOnly: true, max: 1000000000000, digits: 12, min: 0 });
            $("#txtVAT").jqxNumberInput({ height: '32px', value: 0, max: 100, decimalDigits: 0, digits: 3, min: 0, symbol: '%', symbolPosition: 'right' });
            $("#txtTotalAmount").jqxNumberInput({ height: '34px', value: 0, readOnly: true, max: 1000000000000, digits: 12, min: 0 });
            //$("#txtDiscountValue").jqxNumberInput({ height: '34px', value: 0, readOnly: true, max: 1000000000000, digits: 12, min: 0 });
            $("#txtDeposit").jqxNumberInput({ height: '34x', value: 0, max: 100000000000, digits: 12, min: 0 });
            $("#txtDeliveryFee").jqxNumberInput({ height: '34px', value: 0, max: 100000000000, digits: 12, min: 0 });
            $("#ccbProduct").on('change', function (event) {
                if (event.args) {
                    var item = event.args.item;
                    if (item) {

                        //$("#ccbProduct").jqxComboBox('focus');
                        $.ajax({
                            type: "POST",
                            url: 'orders.aspx/GetProduct',
                            data: "{code:'" + item.value + "'}",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (data) {
                                //alert(data.d.ProductName);
                                $('#txtProductName').val(data.d.ProductName);
                                $('#txtPrice').val(data.d.Price);
                                $('#productid').val(data.d.ProductID);

                                $('#txtProductName').prop('readonly', true);
                                $('#txtPrice').jqxNumberInput({ readOnly: true });
                                $("#txtQty").jqxComboBox('focus');
                            }
                        });
                    }
                    else {

                        $('#txtProductName').prop('readonly', false);
                        $('#txtPrice').jqxNumberInput({ readOnly: false });
                    }
                }
            });
            loadProductGroup();
            function loadProductGroup() {
                $.ajax({
                    type: "POST",
                    url: "Orders.aspx/LoadTree",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        if (data.d != undefined) {
                            var html = "<ul>";
                            $.each(data.d, function (i, item) {
                                if (item.ProductGroupName != undefined) {
                                    if (i == 0) html += "<li  item-selected='true' item-expanded='true' item-value='" + item.ProductGroupID + "'>" + item.ProductGroupName;
                                    else html += "<li item-expanded='true' item-value='" + item.ProductGroupID + "'>" + item.ProductGroupName;
                                    //alert(item.children.count);
                                    if (item.children != "") {
                                        html += "<ul>";
                                        html += getChild(item.children);
                                        html += "</ul>";
                                    }
                                    html += "</li>";
                                }
                            });
                            html += "</ul>";
                        }
                        $("#jqxTree").append(html);
                        $("#dropDownButton").jqxDropDownButton({ width: 150, height: 20 });
                        $('#jqxTree').on('select', function (event) {
                            var args = event.args;
                            var item = $('#jqxTree').jqxTree('getItem', args.element);
                            $("#groupid").val(item.value);
                            var dropDownContent = '<div style="position: relative; margin-left: 3px; margin-top: 5px;">' + item.label + '</div>';
                            $("#dropDownButton").jqxDropDownButton('setContent', dropDownContent);
                            loadProduct();
                        });
                        $("#jqxTree").jqxTree({ height: 220 });
                    }
                });
            }
            function getChild(child) {
                var html = "";
                if (child != "") {
                    $.each(child, function (i, item) {
                        html += "<li item-expanded='true' item-value='" + item.ProductGroupID + "'>" + item.ProductGroupName;
                        if (item.children != "") {
                            html += "<ul>";
                            html += getChild(item.children);
                            html += "</ul>";
                        }
                        html += "</li>";
                    });
                }
                return html;
            }
        });
    </script>
    <script>
        function giao(a) {
            if (a == 0) {
                //document.getElementById('ContentPlaceHolder1_address_giao').style.visibility = "hidden";
                $('#txt_name_other').attr('disabled', 'disabled');
                $('#txt_phone_other').attr('disabled', 'disabled');
                $('#ContentPlaceHolder1_txt_address_other').attr('disabled', 'disabled');
            }
            else {
                $('#txt_name_other').removeAttr('disabled');
                $('#txt_phone_other').removeAttr('disabled');
                $('#ContentPlaceHolder1_txt_address_other').removeAttr('disabled');
            }
        }

    </script>
</asp:Content>
